package com.sc.nft.admin.controller;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import com.sc.nft.annotation.SysMemberLogin;
import com.sc.nft.annotation.UserLogin;
import com.sc.nft.dao.ExitConsensusUserDao;
import com.sc.nft.dao.UserInfoDao;
import com.sc.nft.entity.*;
import com.sc.nft.entity.dto.*;
import com.sc.nft.entity.vo.*;
import com.sc.nft.enums.RedisKeyEnum;
import com.sc.nft.exception.GlobalException;
import com.sc.nft.exception.GlobalRunTimeException;
import com.sc.nft.service.UserConsensusService;
import com.sc.nft.sup.PageResult;
import com.sc.nft.sup.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author 朱梦晨
 * @Description:
 * @date 2024-10-15
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/admin/userConsensus")
@Api(tags = "共识度")
public class UserConsensusController{


    private final UserConsensusService userConsensusService;
    private final UserInfoDao userInfoDao;
    private final ExitConsensusUserDao exitConsensusUserDao;
    private final Redisson redisson;


    @PostMapping(value="/page", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "admin用户共识度列表",notes="admin用户共识度列表", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public PageResult<UserConsensusPageVO> getUserConsensusAdminPage(@Valid @RequestBody UserCollectionConsensusDTO dto){
        return PageResult.success(userConsensusService.getUserConsensusAdminPage(dto.toMp(),dto.getUserTel()));
    }

    @PostMapping(value="/userConsensusConsensus", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "用户生态藏品共识度",notes="用户生态藏品共识度", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @SysMemberLogin
    public Result<List<UserCollectionConsensusListVO>> getUserCollectionConsensusAdminList(@Valid @RequestBody UserConsensusConsensusAdminListDTO dto){
        return PageResult.success(userConsensusService.getUserCollectionConsensusAdminList(dto.getUserId()));
    }


    @ApiOperation(value = "共识度调整", notes = "共识度调整", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/consensusChange", produces = MediaType.APPLICATION_JSON_VALUE)
    @UserLogin
    public Result consensusChange(@RequestBody UserCollectionConsensusUpdateDTO dto) throws GlobalException {

        UserInfo user = userInfoDao.getOneByUserTel(dto.getUserTel());
        if (ObjectUtil.isNull(user)){
            return Result.fail("用户不存在");
        }
        ExitConsensusUser exitConsensusUser = exitConsensusUserDao.getByUserId(user.getId());
        if(ObjectUtil.isNotNull(exitConsensusUser)&&exitConsensusUser.getStatus()) {
            return Result.fail("用户不在共识区");
        }
        BigDecimal consensusNum = dto.getConsensusNum();
        if (dto.getType().getIsAdd() == -1){
            consensusNum = consensusNum.negate();
        }
        userConsensusService.adjustConsensusService(user.getId(),dto.getCollectionId(),consensusNum, dto.getType(),dto.getRemark(),null);
        return Result.success();
    }



    @ApiOperation(value = "共识度表格解析", notes = "共识度表格解析", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/excelPassing", produces = MediaType.APPLICATION_JSON_VALUE)
    public Result<UserCollectionConsensusExcelParsingVO> excelPassing(MultipartFile file,@RequestParam(value = "collectionId") Long collectionId){
        Assert.notNull(file,()->new GlobalRunTimeException("文件不能为空"));

        UserCollectionConsensusExcelParsingVO excelParsingVO;

        RLock lock = redisson.getLock(RedisKeyEnum.BATCH_ADJUST_CONSENSUS.getKey());
        try {
            boolean res = lock.tryLock(10, TimeUnit.SECONDS);
            if (res) {
                excelParsingVO = userConsensusService.excelPassing(file,collectionId);
            }else{
                return Result.fail("请稍后重试!");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            throw new GlobalRunTimeException("系统超时");
        } finally {
            lock.unlock();
        }

        return Result.success(excelParsingVO);
    }


    @ApiOperation(value = "批量共识度", notes = "批量共识度", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/batchConsensusChange", produces = MediaType.APPLICATION_JSON_VALUE)
    public Result<UserCollectionConsensusExcelParsingVO> batchConsensusChange(@RequestBody UserCollectionConsensusBatchUpdateDTO dto){

        RLock lock = redisson.getLock(RedisKeyEnum.BATCH_ADJUST_CONSENSUS.getKey());
        try {
            boolean res = lock.tryLock(10, TimeUnit.SECONDS);
            if (res) {
                List<@Valid UserCollectionConsensusBatchUpdateListDTO> dataList = dto.getDataList();
                for (UserCollectionConsensusBatchUpdateListDTO userCollectionConsensusBatchUpdateListDTO : dataList) {
                    BigDecimal consensusNum = userCollectionConsensusBatchUpdateListDTO.getConsensusNum();
                    if (dto.getType().getIsAdd() == -1){
                        consensusNum = consensusNum.negate();
                    }
                    userConsensusService.adjustConsensusService(userCollectionConsensusBatchUpdateListDTO.getUserId(),dto.getCollectionId(),consensusNum, dto.getType(),dto.getRemark(),null);
                }
            }else{
                return Result.fail("请稍后重试!");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            throw new GlobalRunTimeException("系统超时");
        } finally {
            lock.unlock();
        }

        return Result.success();
    }


}



